const express = require('express');
const router = express.Router();
const { getToken } = require('../token/token');
const connect = require('../MySQL/connect');
router.post('/', (req, res) => {
  const tokenResult = getToken(req.headers.authorization);
  if (!tokenResult.boolean) {
    return res.status(405).send(tokenResult.msg);
  }
  const currentPage = req.body.currentPage || 1;
  const pageSize = req.body.pageSize || 10;
  const startIndex = (currentPage - 1) * pageSize;
  const { find } = req.body
  const sql = `SELECT * FROM STUDENTS LIMIT ${startIndex}, ${pageSize};`;
  const isObj = (obj) => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;
  if (isObj(find)) {
    connect.query(sql, (error, result) => {
      if (error) {
        console.error('数据库查询错误:', error);
        return res.status(500).send({ msg: '服务器内部错误' });
      }
      const totalCountSql = 'SELECT COUNT(*) as totalCount FROM STUDENTS;';
      connect.query(totalCountSql, (error, countResult) => {
        if (error) {
          console.error('数据库查询错误:', error);
          return res.status(500).send({ msg: '服务器内部错误' });
        }
        const totalCount = countResult[0].totalCount;
        const totalPages = Math.ceil(totalCount / pageSize);
        if (result.length === 0) {
          return res.status(404).send({ msg: '数据获取失败，请检查分页数据' });
        }
        return res.status(200).send({
          msg: `请求成功: 当前第${currentPage}页，一共${pageSize}条数据`,
          totalPages,//总页数
          currentPage, //当前页数
          pageSize, //数据条数
          students: result, //查询结果
        });
      });
    });
  } else {
    // 构建 WHERE 子句，使用模糊查询
    const whereClauses = Object.keys(find).map(key => {
      return `${key} LIKE '%${find[key]}%'`;
    });

    const whereClause = whereClauses.length > 0 ? `WHERE ${whereClauses.join(' AND ')}` : '';

    const sql = `SELECT * FROM STUDENTS ${whereClause} LIMIT ${startIndex}, ${pageSize};`;

    connect.query(sql, (error, result) => {
      if (error) {
        console.error('数据库查询错误:', error);
        return res.status(500).send({ msg: '服务器内部错误' });
      }

      const totalCountSql = `SELECT COUNT(*) as totalCount FROM STUDENTS ${whereClause};`;

      connect.query(totalCountSql, (error, countResult) => {
        if (error) {
          console.error('数据库查询错误:', error);
          return res.status(500).send({ msg: '服务器内部错误' });
        }

        const totalCount = countResult[0].totalCount;
        const totalPages = Math.ceil(totalCount / pageSize);

        if (result.length === 0) {
          return res.status(404).send( '数据获取失败，请检查分页数据' );
        }
        console.log(sql);
        return res.status(200).send({
          msg: `请求成功: 当前第${currentPage}页，一共${pageSize}条数据`,
          totalPages,
          currentPage,
          pageSize,
          students: result,
        });
      });
    });
  }
});
module.exports = router;
